package group.rober.jeki.listener.saber;

import group.rober.auth.holder.AuthHolder;
import group.rober.saber.jdbc.accessor.listener.UpdateListener;
import group.rober.saber.kit.BeanKit;
import group.rober.saber.kit.DateKit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Map;

public class WhenAndWhoUpdateListener <T> implements UpdateListener<T>{
    protected Logger logger = LoggerFactory.getLogger(getClass());

    public void before(T data) {
        if(data instanceof List){
            fillDataList((List)data);
        }else if(data instanceof Map){
            fillMap((Map)data);
        }else{
            fillBean(data);
        }
    }

    public void after(T data) {

    }

    protected void fillDataList(List<Object> dataList){
        for(Object object : dataList){
            if(object instanceof Map){
                fillMap((Map)object);
            }else{
                fillBean(object);
            }
        }
    }
    protected void fillBean(Object bean){
        Object value = BeanKit.getPropertyValue(bean,"createdTime");
        if(value==null)BeanKit.setPropertyValue(bean,"createdTime", DateKit.now());
        BeanKit.setPropertyValue(bean,"updatedTime",DateKit.now());

        if(AuthHolder.getUser()!=null){
            if(BeanKit.getPropertyValue(bean,"createdBy")==null){
                BeanKit.setPropertyValue(bean,"createdBy",AuthHolder.getUser().getId());
            }
            BeanKit.setPropertyValue(bean,"updatedBy",AuthHolder.getUser().getId());
        }
    }

    protected void fillMap(Map<String,Object> bean){
        Object value = bean.get("createdTime");
        if(value==null)bean.put("createdTime", DateKit.now());
        bean.put("updatedTime", DateKit.now());

        if(AuthHolder.getUser()!=null){
            if(BeanKit.getPropertyValue(bean,"createdBy")==null){
                bean.put("createdBy",AuthHolder.getUser().getId());
            }
            bean.put("updatedBy",AuthHolder.getUser().getId());
        }
    }
}
